package com.thinkgem.jeesite.modules.sys.interceptor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.TokenUtils;
import com.thinkgem.jeesite.modules.sys.service.SysTokenService;

/**
 * 登录验证controller
 * @author Jack
 * @date 2017年9月25日 下午2:55:27
 * @description 
 */
public class TokenInterceptor implements HandlerInterceptor{
	
	private static final String ERROR_415 = "[415]";	//授权失败
	private static final String ERROR_400 = "[400]";	//参数不合法
	
	@Autowired
	SysTokenService sysTokenService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		String url = request.getRequestURI();
		if(url.contains("genToken")){
			//不拦截获取token的请求
			return true;
		}
		if(url.contains("/a/")){
			//不拦截前台jsp的所有请求
			return true;
		}
		
		//处理请求前判断是否有token信息
		if(StringUtils.isBlank(request.getParameter("token")) || StringUtils.isBlank(request.getParameter("appid"))){
			response.setStatus(400);
			ServletOutputStream os = response.getOutputStream();
			 os.write(ERROR_400.getBytes());
			 os.flush();
			 os.close();
			return false;
		}
		//校验token
		if(TokenUtils.checkToken(request.getParameter("appid"), request.getParameter("token"))){
			return true;
		}
		//校验失败
		 ServletOutputStream os = response.getOutputStream();
		 response.setStatus(415);
		 os.write(ERROR_415.getBytes());
		 os.flush();
		 os.close();
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		//处理请求后，渲染页面前
		System.out.println("请求返回");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		//视图渲染结束了，请求处理完毕
		System.out.println("结束请求");
	}
	
}
